package timer

import (
	"fmt"
	"time"
)

//BeginTimerThrd 开始定时器线程 toInteral是否在正分钟运行 如05,15,20之类
func BeginTimerThrd(periodSec int, runAtOnce bool, toInteral bool, fun func()) {
	go thrd(periodSec, runAtOnce, toInteral, fun)
}
func run(periodSec int, fun func()) {
	timer := time.NewTimer(time.Duration(periodSec) * time.Second)
	for {
		<-timer.C
		fun()
		timer.Reset(time.Duration(periodSec) * time.Second)
	}
}
func thrd(periodSec int, runAtOnce bool, toInteral bool, fun func()) {
	if runAtOnce {
		go fun()
	}
	if toInteral && 60%periodSec == 0 {
		//minute := now.Minute()
		now := time.Now()
		sec := now.Second()
		sLeftTen := 10 - sec%10
		sLeft15 := 15 - sec%15
		left := sLeft15
		if sLeftTen < sLeft15 {
			left = sLeftTen
		}
		fmt.Println("__________now sec:", sec, " sleep ", left)
		time.Sleep(time.Duration(left) * time.Second)
		run(periodSec, fun)
	}
	run(periodSec, fun)
}
